var express = require('express');
var router = express.Router();
var config = require('../config/db')
var MongoClient = require('mongodb').MongoClient
var passport=require('passport')

router.get('/getProductByProductId', async function (req, res, next) {
    var pid = parseInt(req.query.productId)         //1.获取请求的商品编号
    console.log('id:', pid)
    //2.连接数据库
    let client = await MongoClient.connect(config.url)      //获取数据库连接对象
    let db = client.db()
    let product = await db.collection('books').findOne({books_id: pid })    //获取所有商品数据
    console.log('product:', product)
    if (product) {
        res.json({ code: 200, message: 'ok', data: product });
    } else {
        res.json({ code: 200, message: 'error' });
    }
});

/*获取所有商品*/
router.get('/getAllProducts', async function (req, res, next) {
    let client = await MongoClient.connect(config.url)      //获取数据库连接对象
    let db = client.db()
    let products = await db.collection('productsAll').find({}).toArray()    //获取所有商品数据
    console.log('products:', products)
    if (products.length > 0) {
        res.json({ code: 200, message: 'ok', data: products });
    } else {
        res.json({ code: 200, message: 'error' });
    }
});
//测试添加数据的接口
router.post('/addData', async function (req, res, next) {
    let data = req.body
    let client = await MongoClient.connect(config.url) 
    let db = client.db()
    let result = await db.collection('myNew').insertOne(data) 
    res.json({code:200,message:'ok',data:result})
});
module.exports = router;